package com.mashibing.helloworld;


import com.mashibing.util.RabbitMQConnectionUtil;
import com.rabbitmq.client.*;
import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer {
    @Test
    public void consume() throws IOException, TimeoutException, InterruptedException {
        //1.获取连接对象
        Connection connection = RabbitMQConnectionUtil.getConnection();
        //2.构建channel
        Channel channel = connection.createChannel();

        //3.构建队列
        channel.queueDeclare(Publisher.QUEUE_NAME, false, false, false, null);

        //4.监听消息
        DefaultConsumer callback = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者收到消息：" + new String(body, "UTF-8"));
            }
        };
        channel.basicConsume(Publisher.QUEUE_NAME, true, callback);
        System.out.println("开始监听队列");
        System.in.read();
        channel.close();
        connection.close();

    }
}
